/**
 * 药品数据初始化脚本
 * 为数据库添加基础药品数据
 */

import { connectMongoDB } from '../config/mongodb';
import { DrugInfo } from '../models/mongodb-schemas';

const drugData = [
  // 抗生素类
  {
    drugId: 'drug_001',
    name: '阿莫西林胶囊',
    specification: '0.25g×24粒',
    manufacturer: '华北制药集团',
    category: 'antibiotics',
    indication: '敏感菌所致的呼吸道感染、尿路感染、皮肤软组织感染等',
    contraindications: ['青霉素过敏者禁用'],
    sideEffects: ['恶心', '呕吐', '腹泻', '皮疹'],
    warnings: ['对青霉素过敏史慎用', '遵医嘱完成疗程'],
    usage: '口服',
    dosage: '成人一次0.5g，每8小时一次',
    storage: '密封保存',
    price: 15.80,
    image: '/images/drugs/amoxicillin.jpg',
    isPrescription: true,
    inStock: true,
    stockQuantity: 150,
    tags: ['抗生素', '感染', '呼吸道'],
    description: '广谱青霉素类抗生素，对革兰阳性菌和部分革兰阴性菌有效',
    rating: 4.2,
    reviewCount: 89
  },
  {
    drugId: 'drug_002',
    name: '头孢克肟分散片',
    specification: '0.1g×6片',
    manufacturer: '石药集团',
    category: 'antibiotics',
    indication: '敏感菌所致的急性咽炎、急性扁桃体炎、急性支气管炎等',
    contraindications: ['头孢菌素过敏者禁用'],
    sideEffects: ['腹泻', '恶心', '头痛'],
    warnings: ['青霉素过敏者慎用', '饭后服用'],
    usage: '口服',
    dosage: '成人一次0.1g，每12小时一次',
    storage: '密封，在干燥处保存',
    price: 28.50,
    image: '/images/drugs/cefixime.jpg',
    isPrescription: true,
    inStock: true,
    stockQuantity: 120,
    tags: ['抗生素', '头孢', '呼吸道感染'],
    description: '第三代头孢菌素，抗菌谱广，口服吸收良好',
    rating: 4.5,
    reviewCount: 156
  },

  // 止痛药类
  {
    drugId: 'drug_003',
    name: '布洛芬缓释胶囊',
    specification: '0.3g×10粒',
    manufacturer: '中美史克制药',
    category: 'analgesics',
    indication: '用于缓解轻至中度疼痛如头痛、关节痛、偏头痛、牙痛、肌肉痛、神经痛、痛经',
    contraindications: ['消化性溃疡活动期', '对NSAIDs过敏者'],
    sideEffects: ['胃肠不适', '头晕', '皮疹'],
    warnings: ['饭后服用', '不宜与其他NSAIDs合用'],
    usage: '口服',
    dosage: '成人一次0.3g，每12小时一次',
    storage: '密封保存',
    price: 22.90,
    image: '/images/drugs/ibuprofen.jpg',
    isPrescription: false,
    inStock: true,
    stockQuantity: 200,
    tags: ['止痛', '解热', '消炎'],
    description: '非甾体抗炎药，具有解热、镇痛、抗炎作用',
    rating: 4.7,
    reviewCount: 234
  },
  {
    drugId: 'drug_004',
    name: '对乙酰氨基酚片',
    specification: '0.5g×12片',
    manufacturer: '华润三九医药',
    category: 'analgesics',
    indication: '用于普通感冒或流行性感冒引起的发热，也用于缓解轻至中度疼痛',
    contraindications: ['严重肝肾功能不全者'],
    sideEffects: ['偶见皮疹', '恶心', '呕吐'],
    warnings: ['不得超量或长期服用', '肝功能不全者慎用'],
    usage: '口服',
    dosage: '成人一次0.5-1g，每4-6小时一次',
    storage: '密封保存',
    price: 8.50,
    image: '/images/drugs/paracetamol.jpg',
    isPrescription: false,
    inStock: true,
    stockQuantity: 300,
    tags: ['解热', '止痛', '感冒'],
    description: '解热镇痛药，对乙酰氨基酚为主要成分',
    rating: 4.3,
    reviewCount: 567
  },

  // 感冒药类
  {
    drugId: 'drug_005',
    name: '999感冒灵颗粒',
    specification: '10g×9袋',
    manufacturer: '华润三九医药',
    category: 'cold',
    indication: '解热镇痛。用于感冒引起的头痛、发热、鼻塞、流涕、咽痛等症状',
    contraindications: ['对本品过敏者禁用'],
    sideEffects: ['偶见困倦', '口干', '恶心'],
    warnings: ['服药期间不得饮酒', '不宜长期服用'],
    usage: '开水冲服',
    dosage: '成人一次1袋，一日3次',
    storage: '密封，置阴凉干燥处',
    price: 18.80,
    image: '/images/drugs/ganmaolin.jpg',
    isPrescription: false,
    inStock: true,
    stockQuantity: 180,
    tags: ['感冒', '解热', '中成药'],
    description: '中西药复方制剂，快速缓解感冒症状',
    rating: 4.4,
    reviewCount: 412
  },
  {
    drugId: 'drug_006',
    name: '板蓝根颗粒',
    specification: '10g×12袋',
    manufacturer: '广州白云山',
    category: 'cold',
    indication: '清热解毒，凉血利咽。用于肺胃热盛所致的咽喉肿痛、口咽干燥',
    contraindications: ['脾胃虚寒者慎用'],
    sideEffects: ['偶见腹泻', '恶心'],
    warnings: ['糖尿病患者慎用', '孕妇慎用'],
    usage: '开水冲服',
    dosage: '成人一次1袋，一日3-4次',
    storage: '密封，置阴凉干燥处',
    price: 12.50,
    image: '/images/drugs/banlangen.jpg',
    isPrescription: false,
    inStock: true,
    stockQuantity: 250,
    tags: ['清热解毒', '中药', '咽喉'],
    description: '纯中药制剂，清热解毒，预防感冒',
    rating: 4.1,
    reviewCount: 189
  },

  // 消化科药类
  {
    drugId: 'drug_007',
    name: '奥美拉唑肠溶胶囊',
    specification: '20mg×14粒',
    manufacturer: '阿斯利康制药',
    category: 'digestive',
    indication: '胃溃疡、十二指肠溃疡、反流性食管炎、卓-艾综合征',
    contraindications: ['对本品过敏者禁用'],
    sideEffects: ['头痛', '腹泻', '恶心'],
    warnings: ['整粒吞服，不得咀嚼', '长期服用需监测'],
    usage: '口服',
    dosage: '成人一次20mg，一日1-2次',
    storage: '密封，置阴凉干燥处',
    price: 45.60,
    image: '/images/drugs/omeprazole.jpg',
    isPrescription: true,
    inStock: true,
    stockQuantity: 100,
    tags: ['胃药', 'PPI', '抑酸'],
    description: '质子泵抑制剂，强效抑制胃酸分泌',
    rating: 4.6,
    reviewCount: 145
  },
  {
    drugId: 'drug_008',
    name: '健胃消食片',
    specification: '0.5g×24片',
    manufacturer: '江中药业',
    category: 'digestive',
    indication: '健胃消食。用于脾胃虚弱所致的食积，症见不思饮食、嗳腐酸臭、脘腹胀满',
    contraindications: ['对本品过敏者禁用'],
    sideEffects: ['偶见恶心'],
    warnings: ['孕妇慎用', '糖尿病患者慎用'],
    usage: '咀嚼，温开水送服',
    dosage: '成人一次3片，一日3次',
    storage: '密封，置阴凉干燥处',
    price: 16.90,
    image: '/images/drugs/jianwei.jpg',
    isPrescription: false,
    inStock: true,
    stockQuantity: 220,
    tags: ['健胃', '消食', '中成药'],
    description: '中成药，健胃消食，改善消化不良',
    rating: 4.2,
    reviewCount: 298
  },

  // 心血管类
  {
    drugId: 'drug_009',
    name: '硝苯地平缓释片',
    specification: '20mg×30片',
    manufacturer: '拜耳医药',
    category: 'cardiovascular',
    indication: '高血压、心绞痛',
    contraindications: ['心源性休克', '严重主动脉瓣狭窄'],
    sideEffects: ['头痛', '面红', '踝部水肿'],
    warnings: ['不宜突然停药', '定期监测血压'],
    usage: '口服',
    dosage: '成人一次20mg，一日2次',
    storage: '密封，遮光保存',
    price: 38.90,
    image: '/images/drugs/nifedipine.jpg',
    isPrescription: true,
    inStock: true,
    stockQuantity: 80,
    tags: ['降压', '心血管', '钙离子拮抗剂'],
    description: '钙离子拮抗剂，用于治疗高血压和心绞痛',
    rating: 4.4,
    reviewCount: 67
  },

  // 呼吸系统类
  {
    drugId: 'drug_010',
    name: '沙丁胺醇吸入剂',
    specification: '100μg×200喷',
    manufacturer: '葛兰素史克',
    category: 'respiratory',
    indication: '支气管哮喘、慢性阻塞性肺疾病等伴有支气管痉挛的疾病',
    contraindications: ['对本品过敏者禁用'],
    sideEffects: ['手震颤', '心悸', '头痛'],
    warnings: ['不得超量使用', '使用前摇匀'],
    usage: '吸入',
    dosage: '成人一次100-200μg，必要时可重复',
    storage: '避光，25℃以下保存',
    price: 65.80,
    image: '/images/drugs/salbutamol.jpg',
    isPrescription: true,
    inStock: true,
    stockQuantity: 60,
    tags: ['哮喘', '支气管扩张', '吸入剂'],
    description: '短效β2受体激动剂，快速缓解支气管痉挛',
    rating: 4.8,
    reviewCount: 34
  }
];

class DrugDataSeeder {
  
  /**
   * 初始化药品数据
   */
  async seedDrugs(): Promise<void> {
    try {
      console.log('🌱 开始初始化药品数据...');
      
      // 连接数据库
      await connectMongoDB();
      
      // 清除现有药品数据
      await DrugInfo.deleteMany({});
      console.log('  ✅ 清除现有药品数据');
      
      // 插入新的药品数据
      const result = await DrugInfo.insertMany(drugData);
      console.log(`  ✅ 成功插入 ${result.length} 条药品记录`);
      
      // 显示统计信息
      const stats = await DrugInfo.aggregate([
        {
          $group: {
            _id: '$category',
            count: { $sum: 1 },
            avgPrice: { $avg: '$price' }
          }
        },
        {
          $sort: { count: -1 }
        }
      ]);
      
      console.log('\n📊 药品分类统计:');
      const categoryNames = {
        'antibiotics': '抗生素',
        'analgesics': '止痛药',
        'cold': '感冒药',
        'digestive': '消化科',
        'cardiovascular': '心血管',
        'respiratory': '呼吸系统'
      };
      
      stats.forEach(stat => {
        const name = categoryNames[stat._id as keyof typeof categoryNames] || stat._id;
        console.log(`  ${name}: ${stat.count} 种，平均价格: ¥${stat.avgPrice.toFixed(2)}`);
      });
      
      console.log('\n✅ 药品数据初始化完成');
      
    } catch (error) {
      console.error('❌ 初始化药品数据失败:', error);
      throw error;
    }
  }

  /**
   * 更新药品库存
   */
  async updateStock(): Promise<void> {
    try {
      console.log('📦 更新药品库存信息...');
      
      // 随机更新部分药品库存
      const drugs = await DrugInfo.find().limit(5);
      
      for (const drug of drugs) {
        const newStock = Math.floor(Math.random() * 300) + 50;
        await DrugInfo.findByIdAndUpdate(drug._id, {
          stockQuantity: newStock,
          inStock: newStock > 0
        });
      }
      
      console.log('  ✅ 库存信息更新完成');
      
    } catch (error) {
      console.error('❌ 更新库存失败:', error);
      throw error;
    }
  }
}

// 主函数
async function main() {
  const seeder = new DrugDataSeeder();
  
  try {
    await seeder.seedDrugs();
    await seeder.updateStock();
    
    console.log('\n🎉 药品数据库初始化完成！');
    process.exit(0);
    
  } catch (error) {
    console.error('❌ 初始化失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

export default DrugDataSeeder;